/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jl.security.disperse;

import java.security.GeneralSecurityException;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.jl.security.Util;
import com.jl.util.Calculator;

/**
 * 
 * @author LuHongjun
 */
public class DESedeNopadding16 implements IDisperse {

	private byte[] resKey;
	private byte[] data;
	private byte[] key;
	private Key sKey;
	private Cipher cipher;

	@Override
	public byte[] getKey(byte[] key) throws GeneralSecurityException {

		this.key = new byte[key.length];
		System.arraycopy(key, 0, this.key, 0, key.length);

		if (this.data == null || this.data.length == 0) {
			throw new GeneralSecurityException("data length error");
		}

		if (this.key == null || this.key.length == 0) {
			throw new GeneralSecurityException("key length error");
		}

		cipher = Cipher.getInstance("DESede/ECB/NoPadding");
		byte[] key24 = Util.modifyKey16To24(this.key);
		sKey = new SecretKeySpec(key24, "DESede");
		cipher.init(Cipher.ENCRYPT_MODE, sKey);
		resKey = cipher.doFinal(this.data);

		return resKey;
	}

	@Override
	public void initDisData(byte[] disData) {
		if (disData.length != 4 && disData.length != 8 && disData.length != 16) {
			return;
		}

		data = new byte[16];
		if (disData.length == 8) {
			System.arraycopy(disData, 0, data, 0, 8);
			// byte[] dataNot = new Calculator().NOT(data);
			byte[] dataNot = Calculator.not(data);
			System.arraycopy(dataNot, 0, data, 8, 8);
			// System.out.println(HexUtil.toHexXX(this.data));
		} else if (disData.length == 16) {
			System.arraycopy(disData, 0, data, 0, disData.length);
		} else if (disData.length == 4) {

			byte[] add20 = new byte[8];
			System.arraycopy(disData, 0, add20, 0, 4);
			for (int i = 4; i < 8; i++) {
				add20[i] = 0x20;
			}
			System.arraycopy(add20, 0, data, 0, 8);
			// byte[] dataNot = new Calculator().NOT(add20);
			byte[] dataNot = Calculator.not(add20);
			System.arraycopy(dataNot, 0, data, 8, 8);
		}
	}

}
